import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class TestServer03 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket clientSocket = null;
        
        try {
            // 1. 启动TCP服务器，监听端口8002
            serverSocket = new ServerSocket(8002);
            System.out.println("服务器已启动，端口：8002");

            // 2. 等待客户端连接
            clientSocket = serverSocket.accept();
            System.out.println("客户端已连接：" + clientSocket.getRemoteSocketAddress());

            // 3. 获取输入流并读取客户端发送的Teacher集合
            try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream())) {
                // 抑制未经检查的类型转换警告
                @SuppressWarnings("unchecked")
                List<Teacher> teachers = (List<Teacher>) ois.readObject();

                // 4. 遍历并打印Teacher信息
                System.out.println("接收到的老师信息：");
                for (Teacher teacher : teachers) {
                    System.out.println(teacher);
                }

                // 5. 将集合写入本地文件 src/t.txt
                File file = new File("src/t.txt");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs(); // 确保目录存在
                }
                try (ObjectOutputStream oosFile = new ObjectOutputStream(new FileOutputStream(file))) {
                    oosFile.writeObject(teachers);
                    System.out.println("数据已写入文件：" + file.getAbsolutePath());
                }

                // 6. 返回响应 "ok" 给客户端
                try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {
                    bw.write("ok");
                    bw.newLine();
                    bw.flush();
                    System.out.println("已向客户端发送确认响应");
                }
            } catch (ClassNotFoundException e) {
                System.err.println("反序列化失败：未找到Teacher类");
                e.printStackTrace();
            } catch (ClassCastException e) {
                System.err.println("非法数据类型：客户端发送的不是List<Teacher>");
                e.printStackTrace();
            }

        } catch (IOException e) {
            System.err.println("服务器发生IO异常");
            e.printStackTrace();
        } finally {
            // 7. 关闭资源
            try {
                if (clientSocket != null) clientSocket.close();
                if (serverSocket != null) serverSocket.close();
                System.out.println("服务器已关闭");
            } catch (IOException e) {
                System.err.println("关闭资源时发生异常");
                e.printStackTrace();
            }
        }
    }
}